<template>

  <div class="container">
    <div class="card1">
      <div class="title">二维码生成</div>
      <div class="lcontainer">
        <div class="qrleft">
          <div style="font-size: 14px;">二维码信息</div>
          <div style="font-size: 12px;margin-bottom: 5px;margin-top: 20px;text-align: left;">二维码内容</div>
          <textarea placeholder="请输入二维码内容" rows="4" id="qrInfo" v-model="qrInfo" :disabled="isEdit"
            style="width: 100%;background: #F2F3F5;border: none;font-size: 12px;margin-bottom: 15px;padding: 10px;"></textarea>
          <br />
          <div style="font-size: 12px;">纠错等级</div>
          <select v-model="selectedLevel" id="qrLevel" :disabled="isEdit"
            style="width: 40%;background: #F2F3F5;border: none;font-size: 12px;height: 28px;margin-bottom: 15px;">
            <option value="L">L(7%)</option>
            <option value="M">M(15%)</option>
            <option value="Q">Q(25%)</option>
            <option value="H">H(30%)</option>
          </select>
          <br />
        </div>
        <div class="qright">
          <div style="position: relative;display: inline-block;">
            <canvas ref="qrCodeCanvas" :width="qrWidth" :height="qrHeight"></canvas>
            <canvas ref="editableCanvas" v-if="isEdit" :width="qrWidth" :height="qrHeight" @mousedown="startDrawing"
              @mousemove="draw" @mouseup="stopDrawing" @mouseleave="stopDrawing"
              style="position: absolute; top: 0; left: 0; pointer-events: all;"></canvas>
          </div>
          <div style="display: flex;justify-content: space-between;width: 50%;">
            <MButton @click="openDraw" type="submit" style="width: 50px;" v-if="!isEdit" :disabled="!isMake">编辑
            </MButton>
            <MButton @click="save" type="submit" style="width: 50px;" v-if="isEdit">保存</MButton>
            <MButton @click="validateQRCode" type="submit" style="width: 50px;">生成</MButton>
          </div>
        </div>
      </div>
    </div>
    <div class="card2">
      <div style="background: #F4F4F4;height: 95%; padding: 10px;">
        <div class="title">二维码生成列表</div>
        <div style="overflow-y: auto;">
          <div style="display: flex;justify-content: space-between;flex-wrap: wrap;height: 100%;">
            <div v-for="(qr, index) in qrList" :key="index"
              style="width: 30%;background: white;padding: 10px;margin: 10px;height: 55%;border-radius: 5px;">
              <div>
                <div style="display: flex;">
                  <div style="flex:1 1 100px;width: 100px;height: 100px;">
                    <img :src="qr.url" alt="生成的二维码" style="max-height: 100%" />
                  </div>
                  <div style="flex:1 1 200px;padding: 10px;text-align: left;">
                    <div style="font-size: 14px;color: #86909C;">内容</div>
                    <div class="listinfo">
                      {{ qr.info }}</div>
                  </div>
                </div>
                <div style="display: flex;margin-top: 5px;">
                  <div style="flex: 1 1 100px;width: 100px;color: #86909C;">
                    纠错等级:
                    <span style="color: black;">{{ qr.level }}
                    </span>
                  </div>
                  <div style="flex: 1 1 200px; font-size: 14px;color: #86909C;text-align: left;">
                    损毁面积比率:
                    <span style="color: black;">{{ qr.ratio }}
                    </span>
                  </div>
                </div>
              </div>
              <div style="text-align: right;margin-top: 10px;padding-right: 10px;display: flex;">
                <div style="flex: 1 1 100px;">
                  <div :class="qr.state" v-if="qr.state != ''">
                    <img :src="qr.state === 'Success' ? Success : Fail" class="img" />
                    {{ qr.state === "Success" ? "成功" : "失败" }}
                  </div>
                </div>
                <div style="flex: 1 1 100px;">
                  <MButton @click="deleteQr(index)" type="submit"
                    style="width: 50px;background: #F2F3F5;color: #4E5969;">
                    删除</MButton>
                  <MButton @click="identifyQe(qr, index)" type="submit" style="width: 50px;margin-left: 10px;">识别
                  </MButton>
                </div>

              </div>
            </div>
            <img :src="qrCodeUrl" ref="imageRef" alt="生成的二维码" style="max-height: 100%;display: none;" />
          </div>
        </div>

      </div>
    </div>
  </div>

</template>

<script>
import MButton from '../components/MButton.vue'
import QRCode from 'qrcode';
import Jsqr from 'jsqr';
import Success from "@/resource/success.png"
import Fail from "@/resource/error.png"
import { ref, } from 'vue';
export default {
  name: 'QrDestroy',
  props: {
    msg: String
  },
  components: {
    MButton,
  },
  data() {
    return {
      qrWidth: 180, // 二维码宽度
      qrHeight: 180, // 二维码高度
      drawing: false, // 是否正在绘制
      startX: 0, // 绘制起始X坐标
      startY: 0, // 绘制起始Y坐标
      qrInfo: '',
      isEdit: false,
      isMake: false,
      qrList: [],
      selectedLevel: "L",
      qrCodeUrl: "",
      blackRatio: 0,
      blackPixelsCanvas1: 0,
      blackPixelsCanvas2: 0,
    };
  },
  methods: {
    handleAlertClosed() {
      // 这里可以处理弹窗关闭后的逻辑
      this.alertVisible = false;
    },
    async validateQRCode() {

      if (this.qrInfo !== "") {
        this.isMake = true
        QRCode.toCanvas(this.$refs.qrCodeCanvas, this.qrInfo, { width: this.qrWidth, height: this.qrHeight, errorCorrectionLevel: this.selectedLevel }, (error) => {
          if (error) console.error(error);
        });
      } else {

        alert("请输入内容")
      }

    },
    openDraw() {
      this.isEdit = true;
    },
    startDrawing(event) {
      this.drawing = true;
      const rect = this.$refs.editableCanvas.getBoundingClientRect();
      this.startX = event.clientX - rect.left;
      this.startY = event.clientY - rect.top;
    },
    deleteQr(index) {
      this.qrList.splice(index, 1);
    },
    identifyQe(qr, index) {
      const img = this.$refs.imageRef;
      img.src = qr.url
      if (!img) {
        console.log('未获取到图片元素，请检查。');
        return;
      }
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
      const qrCode = Jsqr(imageData, canvas.width, canvas.height);
      console.log("qrCode", qrCode);

      if (qrCode) {
        const a = [...this.qrList]
        a[index].state = "Success"
        this.qrList = a
      } else {
        const a = [...this.qrList]
        a[index].state = "Fail"
        this.qrList = a
      }
    },


    processCanvases(newCanvas, newCtx) {
      const canvas1 = this.$refs.qrCodeCanvas;
      const ctx1 = canvas1.getContext('2d');

      const imageData1 = ctx1.getImageData(0, 0, canvas1.width, canvas1.height).data;
      const imageData2 = newCtx.getImageData(0, 0, newCanvas.width, newCanvas.height).data;

      var d1 = 0;
      var d2 = 0;

      for (let i = 0; i < imageData1.length; i += 4) {
        const r1 = imageData1[i];
        const g1 = imageData1[i + 1];
        const b1 = imageData1[i + 2];
        const a1 = imageData1[i + 3];

        const r2 = imageData2[i];
        const g2 = imageData2[i + 1];
        const b2 = imageData2[i + 2];
        const a2 = imageData2[i + 3];

        if (a1 > 0 && (r1 === 0 && g1 === 0 && b1 === 0)) {
          d1++;
        }

        if (a2 > 0 && (r2 === 0 && g2 === 0 && b2 === 0)) {
          d2++;
        }
      }
      return d2 / d1 || 0

    },
    save() {
      this.isEdit = false
      const newCanvas = document.createElement('canvas');
      newCanvas.width = this.qrWidth;
      newCanvas.height = this.qrHeight;
      const newCtx = newCanvas.getContext('2d');

      newCtx.drawImage(this.$refs.qrCodeCanvas, 0, 0);

      newCtx.globalCompositeOperation = 'source-atop';
      newCtx.drawImage(this.$refs.editableCanvas, 0, 0);
      const imageDataUrl = newCanvas.toDataURL('image/png');
      var difference = 1 - this.processCanvases(newCanvas, newCtx);
      var ratio = (Math.round(difference * 10000) / 100).toFixed(2) + "%";

      this.qrList.push({
        info: this.qrInfo,
        level: this.selectedLevel,
        url: imageDataUrl,
        state: "",
        ratio: ratio
      })

      const canvas = this.$refs.editableCanvas;
      const canvas1 = this.$refs.qrCodeCanvas;
      if (canvas) {
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
      }
      if (canvas1) {
        const ctx = canvas1.getContext('2d');
        ctx.clearRect(0, 0, canvas1.width, canvas1.height);
      }
    },
    draw(event) {
      if (!this.drawing) return;
      const ctx = this.$refs.editableCanvas.getContext('2d');
      const rect = this.$refs.editableCanvas.getBoundingClientRect();
      const currentX = event.clientX - rect.left;
      const currentY = event.clientY - rect.top;

      // 设置绘制样式（例如，白色填充，黑色边框）
      ctx.fillStyle = 'red';
      ctx.globalCompositeOperation = 'source-over'; // 覆盖原有内容

      // 清除之前的绘制（可选，如果你想要连续绘制而不留下痕迹）
      // 注意：这会导致性能问题，特别是在大画布上
      // ctx.clearRect(0, 0, this.qrWidth, this.qrHeight);

      // 绘制矩形来遮挡二维码
      ctx.fillRect(
        Math.min(this.startX, currentX),
        Math.min(this.startY, currentY),
        Math.abs(this.startX - currentX),
        Math.abs(this.startY - currentY)
      );

      // 如果你想要边框，可以取消以下注释
      // ctx.strokeStyle = 'black';
      // ctx.strokeRect(
      //   Math.min(this.startX, currentX),
      //   Math.min(this.startY, currentY),
      //   Math.abs(this.startX - currentX),
      //   Math.abs(this.startY - currentY)
      // );
    },
    stopDrawing() {
      this.drawing = false;
      // 创建一个新的canvas元素  
    },
  },

  setup() {
    const imageRef = ref(null);
    return {
      Success,
      imageRef,
      Fail
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.listinfo {
  font-size: 12px;
  margin-top: 10px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  /* 设置显示的行数 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.Success {
  width: 60px;
  height: 25px;
  font-size: 12px;
  text-align: center;
  margin-left: 10px;
  display: flex;
  align-items: center;
  color: #00B42A;
  background: #E8FFEA;
}

.Fail {
  width: 60px;
  height: 25px;
  font-size: 12px;
  background: #FFECE8;
  text-align: center;
  margin-left: 10px;
  display: flex;
  align-items: center;
  color: #F53F3F;
  ;
}

canvas {
  border: 1px solid #ccc;
  /* 可选，用于可视化边框 */
}

.img {
  width: 15px;
  height: 15px;
  margin: 0 5px;
}

.minput {
  height: 30px;
  border: 1px solid #ffffff;
  background: #F2F3F5;
  border-radius: 2px;
  box-sizing: border-box;
  padding: 0 5px;
}

.defaultTab {
  width: 70px;
  height: 24px;
  font-size: 12px;
  border-radius: 12px;
  color: #4E5969;
  background: white;
}

.selTab {
  width: 70px;
  height: 24px;
  background: #F2F3F8;
  font-size: 12px;
  border-radius: 12px;
  color: #1664FF;
}

.container_set {
  padding: 5px 20px;
}

.save {
  align-items: center;
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 70%;
  height: 20%;
}

.qrimg {
  width: 152px;
  height: 152px;
  border: 1px solid gray;
  margin-bottom: 5%;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.title {
  margin-bottom: 10px;
  text-align: left;
}

.qrleft {
  flex: 1 1 100px;
  text-align: left;
}

.qright {
  flex: 1 1 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.lcontainer {
  display: flex;
  padding: 10px;
  height: 80%;
  text-align: left;
}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 728px;
}

.card2 {
  width: 70%;
  height: 62%;
  margin-bottom: 20px;
  background: green;
  box-shadow: 0 8px 12px rgba(49, 49, 49, 0.3);
  border-radius: 0 0 5px 5px;
  padding: 20px;
  background-color: white;
  transition: box-shadow 0.3s ease;
}

.card1 {
  width: 70%;
  height: 38%;
  margin-top: 10px;
  background: green;
  box-shadow: 0 8px 12px rgba(49, 49, 49, 0.3);
  border-radius: 5px 5px 0 0;
  padding: 20px 20px 0 20px;
  background-color: white;
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
  /* 鼠标悬停时加深阴影效果，营造悬浮起来的感觉 */
}

.card:last-child {
  margin-bottom: 0;

  /* 移除最后一个卡片的底部间距，使其符合要求 */
}

::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  position: absolute;
}

::-webkit-scrollbar-thumb {
  background-color: #8d8c8c9d
}
</style>
